import { constantRoutes } from '@/router'
import { getRouters, getPermissions } from '@/api/role'
import { generateRoutes } from '@/utils'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

const state = {
  routes: [],
  addRoutes: [],
  permission: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PERMISSIONS: (state, permission) => {
    state.permission = permission
  }
}

const actions = {
  generateRoutes({ commit }, role) {
    return new Promise(resolve => {
      let roleId
      roleId = role.roleCode == 'SUPERADMIN' ? role.roleCode : role.id
      // 获取路由
      getRouters(roleId).then(res => {
        const accessedRouters = generateRoutes(res.data.list)
        commit('SET_ROUTES', accessedRouters)
        // 获取权限
        getPermissions(roleId).then(permRes => {
          const accessedPermissions = permRes.data.list
          commit('SET_PERMISSIONS', accessedPermissions)
        })
        resolve(accessedRouters)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
